package org.jeecg.modules.extbpm.listener.task;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.bpm.service.ActivitiService;
import org.jeecg.modules.extbpm.process.entity.ExtActBpmLog;
import org.jeecg.modules.extbpm.process.service.IExtActBpmLogService;

/**
 * @author zhoujf
 * A task has been created. This is thrown when task is fully initialized (before TaskListener.EVENTNAME_CREATE)
 * 	首节点任务被创建时自动执行通过
 *
 */
public class TaskCreatedAutoSubmitListener implements TaskListener {
	
	private static final long serialVersionUID = 1L;
	private static ISysBaseAPI sysBaseAPI;
	private static IExtActBpmLogService extActBpmLogService;
	protected static RuntimeService runtimeService;
	private static ActivitiService activitiService;
	private static TaskService taskService;
	
	static {
		sysBaseAPI = SpringContextUtils.getBean(ISysBaseAPI.class);
		extActBpmLogService = SpringContextUtils.getBean(IExtActBpmLogService.class);
		runtimeService = SpringContextUtils.getBean(RuntimeService.class);
		activitiService = SpringContextUtils.getBean(ActivitiService.class);
		taskService = SpringContextUtils.getBean(TaskService.class);
	}
	
	@Override
	public void notify(DelegateTask delegateTask) {
		try {
        	//如果是流程的第一步，则自动提交
            this.onCreate(delegateTask);
        } catch (Exception ex) {
        }
	}
	
    private void onCreate(DelegateTask delegateTask) throws Exception {
        //如果是流程的第一步，则自动提交
        PvmActivity targetActivity = findFirstActivity(delegateTask.getProcessDefinitionId());
        if (!targetActivity.getId().equals(delegateTask.getExecution().getCurrentActivityId())) {
            return;
        }
        //判断是否存在历史节点,存在说明第一个节点已经自动审批过
    	List<Map<String,Object>> histListNode = activitiService.getHistTaskNodeList(delegateTask.getProcessInstanceId());
    	if(histListNode!=null&&histListNode.size()>0) {
    		return;
    	}
    	//自动审批
//        new AutoCompleteCmd(delegateTask.getId(),delegateTask.getVariables(),"系统自动完成").execute(Context.getCommandContext());
        taskService.complete(delegateTask.getId(),delegateTask.getVariables());
        
        //日志
        String username = JwtUtil.getUserNameByToken(SpringContextUtils.getHttpServletRequest());
        LoginUser user = sysBaseAPI.getUserByName(username);
		String processInstanceId = delegateTask.getProcessInstanceId();
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        ExtActBpmLog bpmlog = new ExtActBpmLog();
		if(processInstance!=null) {
			bpmlog.setBusinessKey(processInstance.getBusinessKey());
			bpmlog.setProcName(processInstance.getName());
		}
//		bpmlog.setOpStatus(opStatus);
		bpmlog.setOpTime(new Date());
//		bpmlog.setOpType(WorkFlowGlobals.BPM_OP_TYPE_1);
		bpmlog.setOpUserId(username);
		if(user!=null){
			bpmlog.setOpUserName(user.getRealname());
		}
		bpmlog.setProcInstId(processInstanceId);
		bpmlog.setRemarks("系统自动完成");
		bpmlog.setTaskDefKey(delegateTask.getTaskDefinitionKey());
		bpmlog.setTaskId(delegateTask.getId());
		bpmlog.setTaskName(delegateTask.getName());
		extActBpmLogService.save(bpmlog);
    }

    public RepositoryService getRepositoryService(){
        return SpringContextUtils.getBean(RepositoryService.class);
    }

    public PvmActivity findFirstActivity(String processDefinitionId) {
        ProcessDefinitionEntity processDefinitionEntity  = (ProcessDefinitionEntity)
                ((RepositoryServiceImpl)getRepositoryService())
                        .getDeployedProcessDefinition(processDefinitionId);

        ActivityImpl startActivity = processDefinitionEntity.getInitial();

        PvmTransition pvmTransition = startActivity.getOutgoingTransitions().get(0);
        PvmActivity targetActivity = pvmTransition.getDestination();

        if (!"userTask".equals(targetActivity.getProperty("type"))) {
            return null;
        }
        return targetActivity;
    }

}
